#!/bin/sh

[ -r /etc/default/usbgx ] && . /etc/default/usbgx

for i in $IMPORT_SCHEMAS; do
    /usr/bin/gadget-import "$i" /etc/usbgx/"$i".schema
done

for script in $(find -L /etc/usbgx.d -type f -exec test -e {} \; -print 2>/dev/null); do
    $script
done

for i in $ENABLED_SCHEMAS; do
    configured_udc=$(eval 'echo ${UDC_FOR_SCHEMA_'"$i"'}')
    if [ -n "${configured_udc}" ] && [ -e "/sys/class/udc/${configured_udc}" ]; then
        echo ${configured_udc} > /sys/kernel/config/usb_gadget/"$i"/UDC
    else
        detected_udc=$(ls /sys/class/udc/)
        if [ -z "${detected_udc}" ]; then
            exit 1
        fi
        echo "${detected_udc}" > /sys/kernel/config/usb_gadget/"$i"/UDC
    fi
done
